<?php
/**
 * 框架异常处理类(用于错误状态抛出,阻断程序进行)
 * panglishan
 * 2020.07.23
 */

namespace App\Exceptions;

use Illuminate\Support\Facades\Config;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class BasicException extends \Exception implements HttpExceptionInterface
{

    protected $message;

    protected $params;

    public function __construct($code, $msg = null, $params = [])
    {
        $this->params = $params;
        if (!$msg) {
            $this->message = $this->getInfo($code, $params);
        } else {
            $this->message = $msg;
        }

        parent::__construct($this->message, $code);
    }

    public function getParams()
    {
        return $this->params;
    }

    public function getInfo($code, $params = [])
    {
        $message = isset(Config::get("codeinfo")[$code]) ? Config::get("codeinfo")[$code] : '错误未知';

        return $this->parseParams($message, $params);
    }

    //解决抛出错误信息被dingo劫持返回500status_code的问题
    public function getStatusCode()
    {
        return 200;
    }

    public function getHeaders()
    {
        return [];
    }

    /**
     * @param  string  $content  模板内容
     * @param  array  $params  变量数组
     * @return string 最终模板
     */
    function parseParams(string $content, array $params): string
    {
        $ret = [];
        $leftDelimiter = '{';
        $rightDelimiter = '}';
        foreach ($params as $k => $v) {
            $ret[$leftDelimiter.$k.$rightDelimiter] = $v;
        }

        return strtr($content, $ret);
    }
}
